package com.frame.hander;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


/**
 * @author LRC
 * @createDate 2015年5月22日
 * @description jdbc数据库连接管理工具类
 */
public class DBHander {
	
	private  String url;
	private  String driver;
	private  String username;
	private  String password;
	//数据库连接线程池
	private  ThreadLocal<Connection> cs = new ThreadLocal<Connection>();
	
	/* 
	 * MYSQL URL
	 * jdbc:mysql://localhost:3306/coms?useUnicode=true&characterEncoding=utf-8
	 * MMSQL URL
	 * jdbc:sqlserver://127.0.0.1:1433;databaseName=wums
	 * ORACLE URL
	 * jdbc:oracle:thin:@172.16.8.139:1521:orcl
	 */
	public static final String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
	public static final String MSSQL_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
	public static final String ORACLE_DRIVER = "oracle.jdbc.driver.OracleDriver";
	
	
	public DBHander(String url, String driver, String username, String password) 
			throws ClassNotFoundException {
		this.url = url;
		this.driver = driver;
		this.username = username;
		this.password = password;
		Class.forName(this.driver);
	}
	public Connection getConnection(){
		Connection con = cs.get();
		if(con==null){
			try {
				con = DriverManager.getConnection(url, username, password);
				cs.set(con);
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException("getConnection error");
			}
		}
		return con;
	}
	public void close(){
		Connection con = cs.get();
		if(con!=null){
			try {
				con.close();
				cs.set(null);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void close(Statement stat){
		if(stat!=null){
			try {
				stat.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
